package hlhj.fhp.tvlib.activitys

import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.google.gson.Gson
import com.gyf.barlibrary.ImmersionBar
import com.liaoinstan.springview.container.DefaultFooter
import com.liaoinstan.springview.container.DefaultHeader
import com.liaoinstan.springview.widget.SpringView
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.shuyu.gsyvideoplayer.GSYVideoManager
import hlhj.fhp.tvlib.R
import hlhj.fhp.tvlib.adapter.NewLiveCommentAdp
import kotlinx.android.synthetic.main.aty_livedetail_new.*
import com.shuyu.gsyvideoplayer.listener.LockClickListener
import com.shuyu.gsyvideoplayer.utils.Debuger
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.tenma.ventures.bean.utils.TMSharedPUtil
import com.tenma.ventures.share.bean.TMLinkShare
import com.tenma.ventures.share.util.TMShareUtil
import hlhj.fhp.tvlib.Contents
import hlhj.fhp.tvlib.customView.GoLoginDialog
import hlhj.fhp.tvlib.customView.LoadingDialog
import hlhj.fhp.tvlib.javabean.*
import hlhj.fhp.tvlib.video.DanmakuVDPlayer
import kotlinx.android.synthetic.main.activity_live_aty_tv.*
import kotlinx.android.synthetic.main.lo_live_detail.*


/**
 * Created by Never Fear   on 2018\9\6 0006.
Never More....
 */
class NewLiveAty :BaseAty(), DanmakuVDPlayer.OnEditClickListener {
    private var url="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
    private lateinit var adp:NewLiveCommentAdp
    private val datas=ArrayList<CommentListBean.DataBean>()
    private var header:View?=null
    private var isPlay=false
    private var izZan=0;
    private var page=1
    private var lid=0
    private var tittle=""
    private var sid=0;
    private var extendStr=""
    private var isColl=0
    private lateinit var loadingDialog:LoadingDialog
    private var orientationUtils: OrientationUtils?=null
    override fun getContentId(): Int {
        return R.layout.aty_livedetail_new
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
      /*  ImmersionBar.with(this)
                .init()*/
        loadingDialog= LoadingDialog(this)

        lid=intent.getIntExtra("id",0)
        if (lid==0){
            val paramStr = intent.getStringExtra("paramStr")
            val paramsBean = Gson().fromJson(paramStr, CollectParamsBean::class.java)
            lid=paramsBean.ID
        }
        spView.footer=DefaultFooter(this)
        spView.header=DefaultHeader(this)
        initView()
        val collectParamsBean = CollectParamsBean()
        collectParamsBean.ID=lid
        val u = CollocIosBean()
        collectParamsBean.ID=lid

        val extendBean = ExtendBean()
        val androidInfoBean = ExtendBean.AndroidInfoBean()
        val iosInfoBean = ExtendBean.IosInfoBean()
        androidInfoBean.isNativeX=true
        androidInfoBean.paramStr=Gson().toJson(collectParamsBean)
        androidInfoBean.src="hlhj.fhp.tvlib.activitys.NewLiveAty"
        androidInfoBean.wwwFolder=""

        iosInfoBean.isNativeX=true
        iosInfoBean.paramStr=Gson().toJson(collectParamsBean)
        iosInfoBean.src="HLHJNewLiveDetilController"
        iosInfoBean.wwwFolder=""
        extendBean.androidInfo=androidInfoBean
        extendBean.iosInfo=iosInfoBean

        extendStr=Gson().toJson(extendBean)
        Log.e("fhp","=============Json${extendStr}")
//        set
    }

    private fun initVideo(u:String) {
        videoPlayer.activity=this
        orientationUtils=OrientationUtils(this, videoPlayer)
        val gsyVideoOption = GSYVideoOptionBuilder()
        gsyVideoOption
//                .setThumbImageView(imageView)
                .setIsTouchWiget(true)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setUrl(u)
                .setAutoFullWithSize(true)
                .setShowFullAnimation(false)
                .setNeedLockFull(true)
                .setCacheWithPlay(false)
                .setVideoTitle(tittle)
                .setVideoAllCallBack(object : GSYSampleCallBack() {
                    override fun onPrepared(url: String?, vararg objects: Any) {
                        super.onPrepared(url, *objects)
                        //开始播放了才能旋转和全屏
                        orientationUtils!!.isEnable = true
                        isPlay = true
                        getDamu()
                    }
                    override fun onQuitFullscreen(url: String?, vararg objects: Any) {
                        super.onQuitFullscreen(url, *objects)
                        Debuger.printfError("***** onQuitFullscreen **** " + objects[0])//title
                        Debuger.printfError("***** onQuitFullscreen **** " + objects[1])//当前非全屏player
                        if (orientationUtils != null) {
                            orientationUtils!!.backToProtVideo()
                        }
                    }
                }).setLockClickListener { view, lock ->
            if (orientationUtils != null) {
                //配合下方的onConfigurationChanged

                orientationUtils!!.isEnable = !lock
            }
        }.build(videoPlayer)
    }

    private fun setlistener(){
        val btShare = header?.findViewById<ImageView>(R.id.btShare)
        btShare?.setOnClickListener {
            val instance = TMShareUtil.getInstance(this)
            val tmLinkShare = TMLinkShare()
            tmLinkShare.thumb="${Contents.IMG_URL+intent.getStringExtra("imgThumb")}"
            tmLinkShare.title=tittle
            tmLinkShare.description=tittle
            tmLinkShare.url="${Contents.BaseUrl+"/hlhjlive/Api/download"}"
            instance.shareLink(tmLinkShare)
        }

        val btZan = header?.findViewById<LinearLayout>(R.id.loZan)
        btZan?.setOnClickListener {
            OkGo.post<String>(Contents.BaseUrl+Contents.ItsGood)
                    .params("token",TMSharedPUtil.getTMToken(this))
                    .headers("token",TMSharedPUtil.getTMToken(this))
                    .params("id",lid)
                    .params("type",1)
                    .execute(object :StringCallback(){
                        override fun onSuccess(response: Response<String>?) {
                            val body = response?.body()
                            val baseBean = Gson().fromJson(body, BaseBean::class.java)
                            if (baseBean.code==1){
                                if (izZan==1){
                                    izZan=0
                                    likeNum.text=(likeNum.text.toString().toInt()-1).toString()
                                }else{
                                    likeNum.text=(likeNum.text.toString().toInt()+1).toString()
                                    izZan=1
                                }
                                setZan(izZan)
                                /*data[helper?.adapterPosition!!].is_laud=0
                                notifyDataSetChanged()*/
                            }else{
                                GoLoginDialog(this@NewLiveAty).show()
                            }
                        }
                    })
        }

        btSendComment.setOnClickListener {
            comment("")
        }
        videoPlayer.backButton.setOnClickListener {
            finish()
        }
        videoPlayer.onEditClickListener=this

        spView.setListener(object :SpringView.OnFreshListener{
            override fun onLoadmore() {
                page++
                getComment()
            }

            override fun onRefresh() {
                page=1
                datas.clear()
                getComment()
            }
        })

        header?.findViewById<ImageView>(R.id.btColl)!!.setOnClickListener {
            if (isColl==1){//已收藏，取消收藏
                OkGo.post<String>(Contents.BaseUrl+Contents.CancelColl)
                        .headers("token",TMSharedPUtil.getTMToken(this))
                        .params("star_id",sid)
                        .execute(object :StringCallback(){
                            override fun onSuccess(response: Response<String>?) {
                                val body = response?.body()
                                val baseBean = Gson().fromJson(body, BaseBean::class.java)
                                if (baseBean.code==200){
                                    isColl=0
                                    header?.findViewById<ImageView>(R.id.btColl)!!.setImageResource(R.drawable.ic_sc_normal)
                                    OkGo.post<String>(Contents.BaseUrl+Contents.rememberColl)
                                            .params("id",lid)
                                            .params("token",TMSharedPUtil.getTMToken(this@NewLiveAty))
                                            .headers("token",TMSharedPUtil.getTMToken(this@NewLiveAty))
                                            .params("type",2)
                                            .params("sid",sid)
                                            .execute(object :StringCallback(){
                                                override fun onSuccess(response: Response<String>?) {

                                                }
                                            })
                                    Toast.makeText(this@NewLiveAty,"取消成功",Toast.LENGTH_SHORT).show()
                                }else{
                                    Toast.makeText(this@NewLiveAty,"取消失败",Toast.LENGTH_SHORT).show()
                                }
                            }
                        })
            }else{//为收藏，添加收藏
                OkGo.post<String>(Contents.BaseUrl+Contents.addColl)
                        .headers("token",TMSharedPUtil.getTMToken(this))
                        .params("member_code",TMSharedPUtil.getTMUser(this).member_code)
                        .params("title",tittle)
                        .params("intro",tittle)
                        .params("app_id",Contents.AppId)
                        .params("article_id",lid)
                        .params("tag","")
                        .params("type",2)
                        .params("pic","${Contents.IMG_URL+intent.getStringExtra("imgThumb")}")
                        .params("extend",extendStr)
                        .execute(object :StringCallback(){
                            override fun onSuccess(response: Response<String>?) {
                                val body = response?.body()
                                try {
                                    val bean = Gson().fromJson(body!!, BaseBean::class.java)
                                    if (bean.code==200){
                                        val collBean = Gson().fromJson(body!!, CollBean::class.java)
                                        if(collBean.code==200){
                                            isColl=1
                                            Toast.makeText(this@NewLiveAty,"收藏成功",Toast.LENGTH_SHORT).show()
                                            sid=collBean.data.star_id
                                            header?.findViewById<ImageView>(R.id.btColl)!!.setImageResource(R.drawable.ic_home_collection_selected)
                                            OkGo.post<String>(Contents.BaseUrl+Contents.rememberColl)
                                                    .params("id",lid)
                                                    .params("token",TMSharedPUtil.getTMToken(this@NewLiveAty))
                                                    .headers("token",TMSharedPUtil.getTMToken(this@NewLiveAty))
                                                    .params("type",2)
                                                    .params("sid",sid)
                                                    .execute(object :StringCallback(){
                                                        override fun onSuccess(response: Response<String>?) {
                                                            val body1 = response?.body()
                                                            val baseBean = Gson().fromJson(body1, BaseBean::class.java)
                                                        }
                                                    })
                                        }else if (collBean.code==500){
                                            GoLoginDialog(this@NewLiveAty).show()
                                        }
                                    }else{
                                        GoLoginDialog(this@NewLiveAty).show()

                                    }

                                }catch (e:Exception){
                                    GoLoginDialog(this@NewLiveAty).show()
                                }

                            }
                        })
            }
        }
    }

    /**
     * 是否收藏
     */
    private fun isColl(){
        OkGo.post<String>(Contents.BaseUrl+Contents.isColl)
                .params("member_code",TMSharedPUtil.getTMUser(this).member_code)
                .params("app_id",Contents.AppId)
                .params("article_id",lid)
                .headers("token",TMSharedPUtil.getTMToken(this))
                .execute(object :StringCallback(){
                    override fun onSuccess(response: Response<String>?) {
                        val body = response!!.body()
                        try {
                            val collBean = Gson().fromJson(body, CollBean::class.java)
                            if (collBean.code==200){
                                if (collBean.msg.contains("未")){
                                    isColl=0
                                    header?.findViewById<ImageView>(R.id.btColl)!!.setImageResource(R.drawable.ic_sc_normal)
                                }else{
                                    isColl=1
                                    sid=collBean.data.star_id
                                    header?.findViewById<ImageView>(R.id.btColl)!!.setImageResource(R.drawable.ic_home_collection_selected)
                                }

                            }
                        }catch (e:Exception){
                            header?.findViewById<ImageView>(R.id.btColl)!!.setImageResource(R.drawable.ic_sc_normal)
                        }
                    }
                })
    }

    override fun onEditClick() {

    }

    override fun sendDanMu(str: String?) {
        if (TMSharedPUtil.getTMToken(this@NewLiveAty).equals("")||TMSharedPUtil.getTMToken(this@NewLiveAty)==null){
            GoLoginDialog(this@NewLiveAty).show()
        }else{
            OkGo.get<String>(Contents.BaseUrl+Contents.SEND_DANMU)
                    .params("token",TMSharedPUtil.getTMToken(this@NewLiveAty))
                    .params("live_id",lid)
                    .params("vote_content",str)
                    .execute(object :StringCallback(){
                        override fun onSuccess(response: Response<String>?) {
                            val str = response?.body()
                            val bean = Gson().fromJson(str, BaseBean::class.java)
                            if (bean?.code==1){

                            }
                        }
                    })
        }
    }

    fun initView(){
        header=LayoutInflater.from(this).inflate(R.layout.lo_live_detail,null)
        adp= NewLiveCommentAdp(datas)
        recyclerview.adapter=adp
        recyclerview.layoutManager=LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
        adp.addHeaderView(header)
        videoPlayer.setUp(url,false,"")
        videoPlayer.btnFull.setOnClickListener {
            //直接横屏
            orientationUtils!!.resolveByClick();
            if (orientationUtils?.isLand!!>0){
                orientationUtils!!.backToProtVideo()
            }
            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
            videoPlayer.startWindowFullscreen(this@NewLiveAty, false, true);
        }
        getData()
        getComment()
        setlistener()
        isColl()
    }
    private fun getDamu() {
        OkGo.get<String>(Contents.BaseUrl+Contents.GET_DANMU)
                .params("live_id",intent.getIntExtra("id",0).toString())
                .execute(object :StringCallback(){
                    override fun onSuccess(response: Response<String>?) {
                        val str = response?.body()
                        val bean = Gson().fromJson(str, DanMuBean::class.java)
                        if (bean?.code==1){
                            videoPlayer.addDanmu(bean)
                        }
                    }
                })
    }

    override fun onPause() {
        videoPlayer.onVideoPause()
        super.onPause()
    }

    override fun onResume() {
        videoPlayer.onVideoResume()
        super.onResume()

    }
    override fun onDestroy() {
        GSYVideoManager.releaseAllVideos()
        super.onDestroy()
    }
    private fun setZan(isZan:Int){
        if (isZan==1){
            imgZan.setImageResource(R.drawable.ic_home_praise_select)
            likeNum.setTextColor(Color.parseColor("#DF3434"))
        }else{
            imgZan.setImageResource(R.drawable.ic_home_praise_normal)
            likeNum.setTextColor(Color.parseColor("#333333"))
        }
    }
    private var isComment=true
    private fun getData(){
        OkGo.get<String>(Contents.BaseUrl + Contents.LIVE_DETAIL)
                .params("live_id", lid)
                .execute(object : StringCallback(){
                    override fun onSuccess(response: Response<String>?) {
                        val str = response?.body()
                        val detailBean = Gson().fromJson(str, LiveDetailBean::class.java)
                        if (detailBean.code==1){
                            header?.findViewById<TextView>(R.id.tvTittle)?.text = detailBean.data.live_title
                            header?.findViewById<TextView>(R.id.tvDes)?.text = detailBean.data.live_desc
                            tittle=detailBean.data.live_title
                            initVideo(detailBean.data.live_source)
                            header?.findViewById<TextView>(R.id.likeNum)?.text = detailBean.data.laud_num.toString()
                            header?.findViewById<TextView>(R.id.commentNum)?.text = detailBean.data.comment_num.toString()
                            isComment = detailBean.data.comment_status==1
                            if (detailBean.data.live_desc.length>40){
                                header?.findViewById<TextView>(R.id.btCheckMore)?.visibility=View.VISIBLE
                            }else{
                                header?.findViewById<TextView>(R.id.btCheckMore)?.visibility=View.GONE
                            }
                            if (detailBean.data.is_laud==1){
                                izZan=1
                                setZan(1)
                            }else{
                                izZan=0
                                setZan(0)
                            }
                            /*if (detailBean.data.vote_status==1){
                                videoPlayer.btEdit.visibility=View.VISIBLE
                            }else if (detailBean.data.vote_status==2){
                                videoPlayer.btEdit.visibility=View.GONE
                            }*/
                        }
                    }
                })
    }

    private fun  getComment(){
        OkGo.get<String>(Contents.BaseUrl+Contents.COMMENT_LIST)
                .params("live_id",lid)
                .params("token",TMSharedPUtil.getTMToken(this))
                .headers("token",TMSharedPUtil.getTMToken(this))
                .params("page",page)
                .execute(object :StringCallback(){
                    override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                        super.onStart(request)
                        loadingDialog.show()
                    }
                    override fun onSuccess(response: Response<String>?) {
                        spView.onFinishFreshAndLoad()
                        loadingDialog.dismiss()
                        val str = response?.body()
                        val listBean = Gson().fromJson(str, CommentListBean::class.java)
                        if (listBean.code==1){
                            datas.addAll(listBean.data)
                            adp.notifyDataSetChanged()
                        }
                    }
                })
    }
    private fun comment(str:String){
        if (etContent.text.isEmpty()){

        }else{
            if (TMSharedPUtil.getTMToken(this).equals("")|| TMSharedPUtil.getTMToken(this)==null){
                GoLoginDialog(this@NewLiveAty).show()
            }else{
                if (!isComment){
                    Toast.makeText(this@NewLiveAty,"暂时不能评论",Toast.LENGTH_SHORT).show()
                    return
                }
                OkGo.get<String>(Contents.BaseUrl+Contents.COMMENT)
                        .params("live_id",lid)
                        .params("content",etContent.text.toString())
                        .params("token",TMSharedPUtil.getTMToken(this@NewLiveAty!!))
                        .execute(object :StringCallback(){
                            override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                                super.onStart(request)
                                loadingDialog.show()

                            }
                            override fun onSuccess(response: Response<String>?) {
                                loadingDialog.dismiss()
                                val str = response?.body()
                                val baseBean = Gson().fromJson(str, BaseBean::class.java)
                                if (baseBean.code==1){
                                    Toast.makeText(this@NewLiveAty,"评论成功", Toast.LENGTH_SHORT).show()
                                    etContent.setText("")
                                    val cView = header?.findViewById<TextView>(R.id.commentNum)
                                    cView?.text=(cView?.text?.toString()!!.toInt()+1).toString()
                                    datas.clear()
                                    getComment()
                                }else if (baseBean.code==500){
                                    GoLoginDialog(this@NewLiveAty).show()
                                }else{
                                    Toast.makeText(this@NewLiveAty,baseBean.msg, Toast.LENGTH_SHORT).show()
                                }
                            }
                        })
            }
        }

    }
}